/** 页面设计器工具栏 */

import { cloneDeep } from 'lodash-es'
import { useMessage } from '@/hooks'
import { computed, nextTick, ref } from 'vue'
import { designUtils, useComDesignStoreWithOut } from '@/store'
import { useCloneNodeInfo } from '/@/store/modules/design/src/utils/clone'

import { CopyPasteTypeEnum } from './enum'
import {
  BwCustomComFrontTypeEnum as BwFrontTypeEnum,
  type BwCustomComStructModel,
} from '@bitwit/base-com-render'
import type { MenuInfo } from 'ant-design-vue/es/menu/src/interface'
import { Modal } from 'ant-design-vue'

export function useCreateFormHeader(emit: Function) {
  const designStore = useComDesignStoreWithOut()
  const { createMessage, createWarningModal } = useMessage()

  /** 是否进行粘贴 */
  const isShowPaste = ref(false)

  /** 粘贴内容 */
  const pasteContent = ref('')

  /** 当前组件插槽列表 */
  const curComSlotList = ref<{ label: string; value: string }[]>([])
  /** 当前选中插槽 */
  const curComSlot = ref('')

  const curDesignFrontInfo = computed(() => {
    const info: Record<string, any> = {}
    const curFront = designStore.curFrontType

    switch (curFront) {
      case BwFrontTypeEnum.pc: {
        info.title = 'pc端'
        info.front = curFront
        info.icon = 'ant-design:laptop-outlined'
        break
      }
      case BwFrontTypeEnum.ios: {
        info.title = '苹果端'
        info.front = curFront
        info.icon = 'ant-design:apple-outlined'
        break
      }
      case BwFrontTypeEnum.android: {
        info.title = '安卓端'
        info.front = curFront
        info.icon = 'ant-design:android-outlined'
        break
      }
    }

    return info
  })

  const onClick = () => {
    const structs = designStore.getStructList
    const nodeId = structs[0].nodeId

    if (nodeId) {
      designStore.onSeleteNodeInfo(nodeId)
      emit('setFormConfig')
    }
  }

  /** 修改设计端 */
  const onChangeFront = (data: MenuInfo) => {
    const curFront = data.key as BwFrontTypeEnum
    if (curFront) {
      designStore.setFrontType(curFront)
    }
  }

  /** 复制 */
  const onCopy = (type: CopyPasteTypeEnum) => {
    if (type === CopyPasteTypeEnum.page) {
      const curDesignInfo = designStore.curDesignInfo
      if (curDesignInfo) {
        // navigator.clipboard
        //   .writeText(
        //     JSON.stringify({
        //       designType: 'customCom',
        //       designInfo: curDesignInfo,
        //       type,
        //     })
        //   )
        //   .then(() => createMessage.success('已复制到剪切板！'))
        //   .catch(() => createMessage.warning('复制到剪切板失败！'))
        const content = JSON.stringify({
          designType: 'customCom',
          designInfo: curDesignInfo,
          type,
        })

        try {
          const dom = document.createElement('input')
          dom.value = content
          document.body.appendChild(dom)
          dom.select()
          document.execCommand('copy')
          document.body.removeChild(dom)
          createMessage.success('复制页面成功')
        } catch (err) {
          console.error(err)
          createMessage.error('复制页面失败')
        }
      } else {
        createWarningModal({
          content: '当前组件还未开始设计，请先进行设计！',
        })
      }
    } else {
      const curCom = designStore.selectNodeEle
      if (!curCom) {
        createMessage.warning('当前没有选中组件提示')
      } else {
        const content = JSON.stringify({
          designType: 'customCom',
          designInfo: curCom,
          type,
        })
        try {
          const dom = document.createElement('input')
          dom.value = content
          document.body.appendChild(dom)
          dom.select()
          document.execCommand('copy')
          document.body.removeChild(dom)
          createMessage.success('复制当前组件成功')
        } catch (err) {
          console.error(err)
          createMessage.warning('复制当前组件失败')
        }
      }
    }
  }

  /** 粘贴 */
  const onPaste = () => {
    const resData = pasteContent.value
    nextTick(() => {
      pasteContent.value = ''
      isShowPaste.value = false
    })
    if (!resData) {
      createMessage.warning('没有复制内容')
      return
    }
    try {
      const cueReadInfo = resData ? JSON.parse(resData) : null
      if (cueReadInfo.designType === 'customCom' && cueReadInfo.designInfo) {
        if (cueReadInfo.type === CopyPasteTypeEnum.page) {
          Modal.confirm({
            title: '粘贴页面',
            content: '会覆盖当前页面配置，是否继续?',
            onOk() {
              designStore.setDesignInfo(cueReadInfo.designInfo)
              createMessage.success('粘贴成功')
            },
            onCancel() {},
          })
        } else {
          const coms: BwCustomComStructModel = useCloneNodeInfo(
            cueReadInfo.designInfo
          )
          /** 当前选中组件 */
          const curCom = designStore.selectNodeEle
          const curStruct = cloneDeep(designStore.getStructList)
          if (!curCom) {
            if (!curStruct?.length) {
              designStore.setStructList([coms])
              createMessage.success('粘贴成功')
            } else {
              coms.parentNodeId = curStruct[0].nodeId
              coms.parentNodeSlotCode = 'default'
              curStruct[0].children?.default?.push?.(coms)
              designStore.setStructList(curStruct)
            }
          } else {
            /** 当前选中组件信息 */
            const nodeInfo = designUtils.findDomNodeInfo(
              curStruct,
              curCom.nodeId
            )
            if (nodeInfo) {
              const { index, node, list, pNode } = nodeInfo
              coms.parentNodeId = node.nodeId
              if (curComSlot.value) {
                coms.parentNodeSlotCode = curComSlot.value
                const _curComSlot = curComSlot.value
                if (node?.children?.[_curComSlot]?.length) {
                  node.children[_curComSlot].push(coms)
                } else {
                  node.children = {
                    ...node.children,
                    [_curComSlot]: [coms],
                  }
                }
                designStore.setStructList(curStruct)
                createMessage.success('粘贴成功')
              } else {
                coms.parentNodeSlotCode = node.parentNodeSlotCode
                const pEnableSlotList = pNode?.enableSlotList
                  ?.filter(
                    (item) => item.visible && item.conventionSlotInfo?.slotCode
                  )
                  .map((item) => item.conventionSlotInfo?.slotCode ?? '')
                if (pNode && pEnableSlotList?.length) {
                  if (list?.length) {
                    list.splice(index + 1, 0, coms)
                  } else {
                    coms.parentNodeSlotCode = pEnableSlotList[0]
                    pNode.children = {
                      ...pNode.children,
                      [pEnableSlotList[0]]: [coms],
                    }
                  }
                  designStore.setStructList(curStruct)
                  createMessage.success('粘贴成功')
                } else {
                  if (list?.length) {
                    list.splice(index + 1, 0, coms)
                    designStore.setStructList(curStruct)
                    createMessage.success('粘贴成功')
                  }
                }
              }
            } else {
              /** 如果没有当前自定义组件页面结构信息 */
              coms.parentNodeId = ''
              coms.parentNodeSlotCode = ''
              if (!curStruct?.length) {
                designStore.setStructList([curCom])
                createMessage.success('粘贴成功')
              } else {
                createMessage.error('找不到对应粘贴组件信息！')
              }
            }
          }
        }
      } else {
        createMessage.error('获取自定义组件信息失败！')
      }
    } catch (error) {
      console.error(error)
      createMessage.error('获取自定义组件信息失败！')
    }
    // navigator.clipboard
    //   .readText()
    //   .then((resData) => {})
    //   .catch(() => createMessage.error('获取自定义组件信息失败！'))
  }

  /** 打开粘贴弹窗 */
  const onShowPaste = () => {
    isShowPaste.value = true
    /** 当前选中组件 */
    const curCom = designStore.selectNodeEle
    const slotList: { label: string; value: string }[] = []
    curCom?.enableSlotList?.forEach((item) => {
      if (item.visible && item.conventionSlotInfo?.slotCode) {
        const slotName = item.conventionSlotInfo.slotName
        const slotCode = item.conventionSlotInfo.slotCode
        slotList.push({
          label: slotName,
          value: slotCode,
        })
      }
    })
    curComSlotList.value = slotList
    curComSlot.value = slotList?.[0]?.value ?? ''
  }

  return {
    BwFrontTypeEnum,
    curDesignFrontInfo,
    isShowPaste,
    pasteContent,
    curComSlotList,
    curComSlot,

    onCopy,
    onPaste,
    onClick,
    onChangeFront,
    onShowPaste,
  }
}
